
package com.android.formula.task;

import android.content.Context;
import android.database.SQLException;
import android.util.Log;

import com.android.formula.model.ResultCode;
import com.android.formula.utils.LogUtils;

/**
 * Create base task to connect with database.
 * 
 * @param <TParam>
 * @param <TProgress>
 * @param <TResult>
 */
public abstract class BaseDatabaseTask<TRequestParams, TResult> extends
        AbstractTask<TRequestParams, Void, TResult> {
    protected static final String TAG = "BaseDatabaseTask";

    protected int mResultCode = ResultCode.HAS_DATA;

    public BaseDatabaseTask(Context context, TRequestParams param, Class<TResult> responType,
            IDataEventHandler<TResult> dataEventHandler) {
        super(context, param, dataEventHandler);
    }

    @SuppressWarnings("unchecked")
    @Override
    protected TResult doInBackground(TRequestParams... params) {
        LogUtils.logError(TAG, "**************** [DBTask] Start... ****************");
        TResult result = null;
        try {
            result = execute();
        } catch (Exception e) {
            mResultCode = ResultCode.UNEXPECTED_EXCEPTION;
            LogUtils.logError(TAG, Log.getStackTraceString(e));
            return null;
        }

        if (result == null) {
            mResultCode = ResultCode.NO_DATA;
            return null;
        }

        return result;
    }

    abstract protected TResult execute() throws SQLException;

    @Override
    public void onPostExecute(TResult result) {
        LogUtils.logError(TAG, "**************** [DBTask] Finish! ****************");
        if (mDataEventHandler == null) {
            return;
        }
        switch (mResultCode) {
            case ResultCode.NO_DATA:
                LogUtils.logInfo(TAG, "[DBTask] Result: No Data");
                mDataEventHandler.onNotifyNoData();
                break;
            case ResultCode.UNEXPECTED_EXCEPTION:
                LogUtils.logInfo(TAG, "[DBTask] Result: Error");
                mDataEventHandler.onNotifyErrorMessage("", "");
                break;
            case ResultCode.HAS_DATA:
                LogUtils.logInfo(TAG, "[DBTask] Result: Has Data");
                mDataEventHandler.onNotifyData(result);
                break;
            default:
                break;
        }
    }
}
